package com.tiancheng.trade.order.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class UtilMass {

    private static ObjectMapper objectMapper = new ObjectMapper();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static String lineToHump(String str, String interval) {
        Pattern linePattern = Pattern.compile(interval + "(\\w)");
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String lineToHump(String str) {
        return lineToHump(str, "_");
    }


    //TODO 优化返回类型List<Map<String, Object>>和 错误提示
    public static List readJson2List(String jsonContent){
        try {
            return objectMapper.readValue(jsonContent, List.class);
        }catch (JsonParseException e) {
            e.printStackTrace();
            return new ArrayList();
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return new ArrayList();
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList();
        }
    }

    //TODO 优化返回类型List<Map<String, Object>>和 错误提示
    public static Map readJson2Map(String jsonContent){
        try {
            return objectMapper.readValue(jsonContent, Map.class);
        }catch (JsonParseException e) {
            e.printStackTrace();
            return new HashMap();
        } catch (JsonMappingException e) {
            e.printStackTrace();
            return new HashMap();
        } catch (IOException e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    public static Timestamp str2SqlTimestamp(String strDate){
        return str2SqlTimestamp(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    //TODO 错误提示
    public static Timestamp str2SqlTimestamp(String strDate, String pattern){

        sdf.setLenient(false);

        if(!pattern.equals("yyyy-MM-dd HH:mm:ss")){
            sdf.applyPattern(pattern);
        }
        try {
            return new Timestamp(sdf.parse(strDate).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            // return new Timestamp(0);
            return null;
        }
    }

}
